/* eslint-disable react/jsx-no-bind */
import { Card } from 'antd'
import { useCallback, useState } from 'react'
import { render } from 'react-dom'

import { TriggerEvent } from './event'
import { TriggerPageview } from './pageview'

declare global {
  interface Window {
    ApmPlusWebClient: typeof import('@apmplus/web').default
  }
}

const $root = document.querySelector('#app')

const init = () => {
  window.ApmPlusWebClient('init', Cypress.env().config)
}

const start = () => {
  window.ApmPlusWebClient('start')
}

const configNewPid = () => {
  window.ApmPlusWebClient.config({
    pid: 'new pid',
  })
}

const triggerCreateAndStart = () => {
  window.ApmPlusWebClient('on', 'init', () => {
    const newClient = window.ApmPlusWebClient.create!()
    newClient.init({
      aid: 666,
      token: '123',
      domain: 'cypress.test',
    })
    newClient.start()
  })
}

const triggerCustomEvent = () => {
  window.ApmPlusWebClient('sendEvent', {
    name: 'custom-event',
    metrics: {
      a: 3,
    },
    categories: {
      b: '3',
    },
  })
}

const triggerCustomLog = () => {
  window.ApmPlusWebClient('sendLog', {
    content: 'custom-event',
    extra: {
      a: 3,
      b: '3',
    },
    level: 'error',
  })
}

const triggerCapture = () => {
  window.ApmPlusWebClient('captureException', new Error('manual captureException'), { extraKey: 'extra info' })
}

const triggerCaptureWithOutExtra = () => {
  window.ApmPlusWebClient('captureException', new Error('captureException with out extra'))
}

const triggerDestroy = () => {
  window.ApmPlusWebClient('destroy')
}

const triggerCustomPerfMetric = () => {
  window.ApmPlusWebClient('sendCustomPerfMetric', {
    name: 'test',
    value: 1,
    extra: {
      isRender: 'no',
    },
  })
}

const onClickLongTask = () => {
  const time = Date.now()
  // eslint-disable-next-line no-constant-condition
  while (true) {
    if (Date.now() - time > 50) {
      break
    }
  }
}

const triggerSenderSetSize = () => {
  window.ApmPlusWebClient('on', 'init', () => {
    window.ApmPlusWebClient?.getSender()?.setSize(50)
    window.ApmPlusWebClient('sendEvent', {
      name: 'set-size',
      metrics: {
        size: window.ApmPlusWebClient?.getSender()?.getSize() || 0,
      },
    })
  })
}

const triggerSenderSetWait = () => {
  window.ApmPlusWebClient('on', 'init', () => {
    window.ApmPlusWebClient?.getSender()?.setWait(1500)
    window.ApmPlusWebClient('sendEvent', {
      name: 'set-wait',
      metrics: {
        wait: window.ApmPlusWebClient?.getSender()?.getWait() || 0,
      },
    })
  })
}

const triggerContextSetonInit = () => {
  window.ApmPlusWebClient('on', 'init', () => {
    window.ApmPlusWebClient?.context?.set('test', '1111')
    window.ApmPlusWebClient('sendEvent', {
      name: 'set-context',
      categories: window.ApmPlusWebClient?.context?.toString(),
    })
  })
}

const onClickRAFError = () => {
  window.requestAnimationFrame(() => {
    throw new Error('raf error')
  })
}

const onClickRICError = () => {
  window.requestIdleCallback(() => {
    throw new Error('ric error')
  })
}

const onClickEventHandlerError = () => {
  document.body.addEventListener('click', () => {
    throw new Error('click error')
  })

  document.body.click()
}

const onClickXHRError = () => {
  const xhr = new XMLHttpRequest()
  xhr.open('GET', 'unexist')
  xhr.onreadystatechange = () => {
    throw new Error('xhr error')
  }
  xhr.send()
}

const triggerXHR2Filter = () => {
  window.ApmPlusWebClient('setFilter', 'xhr', ([, url]) => {
    if (url.includes('/oncollect/http')) return true
    return false
  })
}

const triggerFetchFilter = () => {
  window.ApmPlusWebClient('setFilter', 'fetch', ([, options]) => {
    if (options.body) return true
    return false
  })
}

const triggerErrorFilter = () => {
  window.ApmPlusWebClient('setFilter', 'err', () => false)
}

const App = () => {
  const [state, setState] = useState({ a: { b: '3' } })
  const onClickBlank = useCallback(() => {
    setState(3 as any)
  }, [])

  return (
    <div className="app">
      <style>
        {`* {
          margin: 0;
          padding: 0
        }`}
      </style>
      <Card>
        <h1>Slardar SDK</h1>
        <p>Testing by cypress</p>
        <button id="init" onClick={init}>
          Init
        </button>
        <button id="start" onClick={start}>
          Start
        </button>
        <button id="trigger-create-and-start" onClick={triggerCreateAndStart}>
          trigger-create-and-start
        </button>
        <button id="config-new-pid" onClick={configNewPid}>
          config-new-pid
        </button>
        <button id="longtask_click" onClick={onClickLongTask}>
          LongTask_Click
        </button>
        <TriggerEvent />
        <TriggerPageview />
        <button id="trigger-custom-event" onClick={triggerCustomEvent}>
          trigger-custom-event
        </button>
        <button id="trigger-custom-log" onClick={triggerCustomLog}>
          trigger-custom-log
        </button>
        <button id="trigger-capture" onClick={triggerCapture}>
          trigger-capture
        </button>
        <button id="trigger-capture-without-extra" onClick={triggerCaptureWithOutExtra}>
          trigger-capture-without-extra
        </button>
        <button id="trigger-destroy" onClick={triggerDestroy}>
          trigger-destroy
        </button>
        <button id="trigger-custom-perf-metric" onClick={triggerCustomPerfMetric}>
          trigger-custom-perf-metric
        </button>
        <button id="trigger-sender-setSize" onClick={triggerSenderSetSize}>
          trigger-sender-setSize
        </button>
        <button id="trigger-sender-setWait" onClick={triggerSenderSetWait}>
          trigger-sender-setWait
        </button>
        <button id="trigger-context-set-on-init" onClick={triggerContextSetonInit}>
          trigger-context-set-on-init
        </button>
        <div id="raf_error" onClick={onClickRAFError}>
          RAF error
        </div>
        <div id="ric_error" onClick={onClickRICError}>
          ric error
        </div>
        <div id="click_error" onClick={onClickEventHandlerError}>
          click error
        </div>
        <div id="xhr_error" onClick={onClickXHRError}>
          xhr error
        </div>
        <div id="blank_click" onClick={onClickBlank}>
          Blank_Click
          {state.a.b}
        </div>
        <button id="trigger-set-xhr-2-filter" onClick={triggerXHR2Filter}>
          trigger-set-xhr-2-filter
        </button>
        <button id="trigger-set-fetch-filter" onClick={triggerFetchFilter}>
          trigger-set-fetch-filter
        </button>
        <button id="trigger-set-error-filter" onClick={triggerErrorFilter}>
          trigger-set-error-filter
        </button>
      </Card>
    </div>
  )
}

const delay = new URL(location.href).searchParams.get('delay')
if (delay) {
  setTimeout(() => {
    render(<App />, $root!)
  }, parseInt(delay))
} else {
  render(<App />, $root!)
}
